﻿using System;
using System.Collections.Generic;
using System.Linq;
using Nxg.Blog.Core.Documents;

namespace Nxg.Blog.Core.ViewProjections.Home
{
    public class RecentBlogPostsViewModel
    {
        public IEnumerable<BlogPost> Posts { get; set; }

        public int Page { get; set; }

        public int PageCount { get; set; }
    }

    public class RecentBlogPostsBindingModel
    {
        public RecentBlogPostsBindingModel()
        {
            Page = 1;
            Take = 20;
        }

        public int Page { get; set; }

        public int Take { get; set; }
    }

    public class RecentBlogPostViewProjection : IViewProjection<RecentBlogPostsBindingModel, RecentBlogPostsViewModel>
    {
        private readonly DataContext _context;

        public RecentBlogPostViewProjection(DataContext context)
        {
            _context = context;
        }

        public RecentBlogPostsViewModel Project(RecentBlogPostsBindingModel input)
        {
            var skip = (input.Page - 1) * input.Take;

            var posts = _context
                .Post
                .Where(x => x.Status == PublishStatus.Published && x.PubDate <= DateTime.Now)
                .OrderByDescending(x => x.PubDate);
            var pagedPosts = posts.Skip(skip).Take(input.Take).ToList();

            var total = posts.Count();

            return new RecentBlogPostsViewModel
            {
                Posts = pagedPosts,
                Page = input.Page,
                PageCount = (total / input.Take) + (total % input.Take == 0 ? 0 : 1)
            };
        }
    }
}